package cn.qayy.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.qayy.constants.CollectionConstant;
import cn.qayy.constants.Constant;
import cn.qayy.dto.BasisDTO;
import cn.qayy.dto.BidDTO;
import cn.qayy.dto.Msg;
import cn.qayy.dto.MsgInfo;
import cn.qayy.po.Basis;
import cn.qayy.po.Bid;
import cn.qayy.po.Policy;
import cn.qayy.po.Register;
import cn.qayy.service.IBidService;
import cn.qayy.service.IPolicyService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.ExcelUtils;
import cn.qayy.utils.JsonUtil;
import cn.qayy.utils.ResonseUtils;
import cn.qayy.utils.ServletContextUtils;
import cn.qayy.utils.StringUtil;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.UploadHandler;

/**
 * @author wangyu 中标库
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/bid/") 
public class BidController {
	// 注入service
	@Resource(name = "bidServiceImpl")
	private IBidService bidService = null;

	@Resource(name = "policyServiceImpl")
	private IPolicyService policyService = null;
	
	List<String> multiselectCondi = new ArrayList<String>(); // 可多选的条件


	/***
	 * 批量导入
	 * @param file
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "upload")
	public Object upload(@RequestParam("excelFile") MultipartFile file,HttpServletRequest request) {
		Msg msg = null;
		int listSize = 0; // excel记录数
		try {
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(file, BidDTO.class);
			if (map.get("fail") != null && !map.get("fail").isEmpty()) {// 前台提示消息
				// 验证不通过，前台提示消息
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE, list);
			} else {// DB持久化
				bidService.persistence(map,request,null);
				// 正常操作前台提示消息
				/**用户上传的总记录数**/
				if(map.get("totalCount").get(0) != null) {
					MsgInfo msgInfo = (MsgInfo)map.get("totalCount").get(0);
					listSize = StringUtil.parseInt(msgInfo.getErr_num());
				}
				msg = new Msg(Constant.SUCESSFUL_CODE, "总记录数：" + listSize + "，总成功数：" + listSize + "，请核查！");
			}
		} catch (Exception e) {
			// e.printStackTrace();
			// 异常后的前台提示消息
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	@ResponseBody
	@RequestMapping(value = "selectBidList")
	public String selectBidList(@RequestParam Map<String, Object> condiMap) {
		//对map进行过滤，除去空格
		condiMap = StringUtil.trim4Map(condiMap);
				
		String resultList = "";
		Msg msg = null;
		try {
			multiselectCondi.add("province");
			multiselectCondi.add("city");
			multiselectCondi.add("pack");
			multiselectCondi.add("product");
			multiselectCondi.add("id");
			for (String obj : condiMap.keySet()) {
				if (multiselectCondi.contains(obj)) {
					if (condiMap.get(obj).toString().startsWith("请选择")) {
						condiMap.put(obj.toString(), null);
					} else if (condiMap.get(obj) != null) {
						if (obj.equals("id")) {
							String[] array = StringUtil.strToArray((String) condiMap.get(obj), " ");
							if (array != null) {
								condiMap.put(obj.toString(), array);
							} else {
								condiMap.put(obj.toString(), null);
							}
						} else {
							String[] array = StringUtil.strToArray((String) condiMap.get(obj), ",");
							if (array != null) {
								condiMap.put(obj.toString(), array);
							} else {
								condiMap.put(obj.toString(), null);
							}
						}
					}
				} else if (condiMap.get(obj).equals("")) {
					condiMap.put(obj.toString(), null);
				}
			}
			PageInfo<Map<String, Object>> listMap = bidService.selectBidBy(condiMap);
			resultList = JSONObject.toJSONString(listMap);
			return resultList;
		} catch (Exception e) {
			// 异常后的前台提示消息
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			resultList = JsonUtil.object2json(msg);
		}
		return resultList;
	}

	@ResponseBody
	@RequestMapping(value = "selectBidByID")
	public Object selectBidByID(@RequestParam Integer bidId) {
		String resultList = "";
		Msg msg = null;
		try {
			Bid bid = bidService.selectBidByID(bidId);
			Object obj = JSONObject.toJSON(bid);
			return obj;
		} catch (Exception e) {
			// 异常后的前台提示消息
			//e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			resultList = JsonUtil.object2json(msg);
		}
		return resultList;
	}

	@ResponseBody
	@RequestMapping(value = "changeBid")
	public Object changeBid(BidDTO dto, HttpServletRequest request,String flag) {
		// 返回结果
		Msg msg = null;
		dto.setIsUpdate(flag);
		try {
			// 验证数据
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(dto);
			if (map.get("fail") != null && !map.get("fail").isEmpty()) {
				// 验证不通过，前台提示消息
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE,list);
			} else {// 验证通过，DB持久化
				bidService.persistence(map,request,null);
				msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数："+1+"，总成功数："+1+"，请核查！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	/***
	 * 页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<BidDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(BidDTO.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("中标库",StringUtil.listToStrArray(CollectionConstant.zbk_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	/***
	 * 展示UI页面
	 * @return
	 */
	@RequestMapping(value="ui")
	public String ui() {
		return "bid_search";
	}
	
	/***
	 * 获取待复制的id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectIds")
	public Object selectIds(HttpServletResponse response,HttpServletRequest request) {
		JSONObject json = new JSONObject();
		StringBuilder result=new StringBuilder();
		Msg msg = null;
		try {
			//获取缓存中的筛选条件
			Map<String, Object> params = (Map<String, Object>)DownLoadUtil.get("BidDTO");
			if(params == null) {
				params = new HashMap<String, Object>();
				params.put("t", "1127");
			}
			List<Integer> list = bidService.selectIdsByMap(params);
			if(list != null && list.size()>0) {
				for (Integer id : list) {
					result.append(id+" ");
				}
				result.deleteCharAt(result.toString().length()-1);
			}
		} catch(Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
			return msg;
		}
		json.put("ids", result.toString());
		ResonseUtils.writeResponseByJson(response, json);
		//封装成json返回给前台
		return null;
	}
}
